const { Op } = require('sequelize')
const Carts = require('../model/carts.model')
const Goods = require('../model/goods.model')
class CartsService {
  async createOrUpdate (user_id, goods_id) {
    // 根据user_id和goods_id同时查找, 有没有记录
    let res = await Carts.findOne({
      where: {
        [Op.and]: {
          user_id,
          goods_id
        }
      }
    })
    if (res) {
      // 存在对应记录,将numer+1
      await res.increment('number')
      // 需要重新加载一次，返回结果
      return await res.reload()
    } else {
      // 新增对应记录
      return await Carts.create({
        user_id,
        goods_id
      })
    }
  }
  async getAll (pageNum, pageSize, user_id) {
    // 获取属于该用户的购物车列表
    const offset = (pageNum - 1) * pageSize
    const { count, rows } = await Carts.findAndCountAll({
      where: {
        user_id: user_id,
      },
      offset,
      limit: pageSize * 1,
      attributes: ['id', 'number', 'selected'],
      include: {
        model: Goods,
        attributes: ['id', 'goods_name', 'goods_price', 'goods_img'],
        as: 'goods_info'
      }
    })
    return {
      pageNum,
      pageSize,
      totoa: count,
      list: rows
    }
  }
  async update (params) {
    const { id, number, selected } = params
    // 查询该条数据
    const res = await Carts.findByPk(id)
    if (!res) return ''
    number != undefined ? res.number = number : ''
    selected != undefined ? res.selected = selected : ''
    return await res.save()
  }
  async deleteBatch (ids) {
    return await Carts.destroy({
      where: {
        id: {
          [Op.in]: ids
        }
      }
    })
  }
  async selectAllCart (user_id, flag) {
    return Carts.update({ selected: flag }, {
      where: {
        user_id
      }
    })
  }
}
module.exports = new CartsService()